<?php
namespace Sonkwl\xphp;

use Sonkwl\xphp\router;
use Sonkwl\xphp\config;
use Sonkwl\xphp\dicter;
use Sonkwl\xphp\priver;

class apper{
    private static $reponseType="JSON"; //JSON/TXT

    public static function Request(){
        try{
            $page="index";
            $method=strtolower($_SERVER["REQUEST_METHOD"]);
            if(isset($_GET["p"])){
                $page=$_GET["p"];
            }
            $pages=explode("_",$page);
            // print_r($pages[0]);
            //载入处理文件
            if(!is_file("controler/{$pages[0]}.php")){
                self::Response($res="NG",$message="{$pages[0]}文件不存在");
            }
            include_once "controler/{$pages[0]}.php";
            if(count($pages)==1){
                $func="Default_".$_SERVER["REQUEST_METHOD"];
            }else{
                $func=ucfirst(strtolower($pages[1]))."_".$_SERVER["REQUEST_METHOD"];
            }
            if(!method_exists($pages[0],$func)){
                self::Response($res="NG",$message="{$pages[0]}的方法{$func}不存在");
            }

            //载入数据字典处理
            middler::Run($page);
            priver::Run($page);
            dicter::Run($page);

            if($method=="get"){
                //处理GET缓存
                self::HandlerCacher($method,$page);
            }


            call_user_func("{$pages[0]}::{$func}");
        }catch(Exception $e){
            echo $e->getMessage();
        }
    }

    public static function GetExpTime($cacher){
        if(!preg_match('/^\d+/',$cacher,$metch)){
            self::Response($res="NG",$message="页面缓存设置时间异常");
        }
        $num=$metch[0];
        if(strpos($cacher,"minutes")!==FALSE){
            return time()-$num*60;
        }
        if(strpos($cacher,"hours")!==FALSE){
            return time()-$num*3600;
        }
        if(strpos($cacher,"days")!==FALSE){
            return time()-$num*3600*24;
        }
        return time()-$num;
    }

    public static function HandlerCacher($method,$page){
        if((router::Get($page))["cacher"]==FALSE){
            return;
        }
        $cachefile=md5($_SERVER['REQUEST_URI']);
        if(!is_file("cacher/{$cachefile}.cache") || filemtime("cacher/{$cachefile}.cache")<self::GetExpTime((router::Get($page))["cacher"])){
            ob_start();
            $pages=explode("_",$page);
            if(!is_file("controler/{$pages[0]}.php")){
                self::Response($res="NG",$message="{$pages[0]}文件不存在");
            }
            include_once "controler/{$pages[0]}.php";
            if(count($pages)==1){
                $func="Default_".$_SERVER["REQUEST_METHOD"];
            }else{
                $func=ucfirst(strtolower($pages[1]))."_".$_SERVER["REQUEST_METHOD"];
            }
            if(!method_exists($pages[0],$func)){
                self::Response($res="NG",$message="{$pages[0]}的方法{$func}不存在");
            }
            call_user_func("{$pages[0]}::{$func}");
            $output=ob_get_contents();
            file_put_contents("cacher/{$cachefile}.cache",$output);
            ob_end_clean();
        }
        echo file_get_contents("cacher/{$cachefile}.cache");
        exit;
        //缓存处理
    }

    public static function Response($res="OK",$message="",$data=[]){
        switch (self::$reponseType) {
            case 'JSON':
                echo json_encode([
                    "res"=>$res,
                    "message"=>$message,
                    "data"=>$data
                ],JSON_UNESCAPED_UNICODE);
                break;
            case 'TXT':
                echo "{$res},{$message}";
                break;
            default:
                echo json_encode([
                    "res"=>$res,
                    "message"=>$message,
                    "data"=>$data
                ]);
                break;
        }
        exit;
    }

    public static function Run($reponseType="JSON"){
        router::Run();
        config::Run();
        self::Request();
    }

    //兼容project自动文档配置项目
    public static function Start(){
        $method=strtolower($_SERVER["REQUEST_METHOD"]);
        if(!isset($_GET["p"])){
            self::Response($res="NG",$message="入口错误，没有定义p",$data=[]);
        }
        $pages=explode("_",$_GET["p"]);
        if(count($pages)!=2){
            self::Response($res="NG",$message="入口错误，p必须是class_func模式",$data=[]);
        }
        $class=$pages[0];
        $func=$_SERVER["REQUEST_METHOD"]."_".$pages[1];

        //config载入
        config::Run();

        //过滤，有者处理
        if(is_file("filter/default.php")){
            include_once "filter/default.php";
        }
        if(is_file("filter/{$method}_".$_GET["p"].".php")){
            include_once "filter/{$method}_".$_GET["p"].".php";
        }

        //数据验证，必须
        if(!is_file("interfacer/{$method}_".$_GET["p"].".php")){
            self::Response($res="NG",$message="验证文件不存在{$method}_".$_GET["p"],$data=[]);
        }
        include_once "interfacer/{$method}_".$_GET["p"].".php";

        //权限验证，有着处理
        if(is_file("priver/{$method}_".$_GET["p"].".php")){
            include_once "priver/{$method}_".$_GET["p"].".php";
        }else{
            //无指定权限
            if(is_file("priver/default.php")){
                //默认权限
                include_once "priver/default.php";
            }
        }

        //调用处理函数
        if(!is_file("controler/{$class}.php")){
            self::Response($res="NG",$message="处理文件不存在{$class}",$data=[]);
        }
        include_once "controler/{$class}.php";
        if(!method_exists($class,$func)){
            self::Response($res="NG",$message="函数不存在{$class}.{$func}",$data=[]);
        }
        call_user_func("{$class}::{$func}");
    }
}
?>